<template>
  <div>
    <el-dialog
      :title="{ add: '新增部门', look: '编辑部门' }[mode]"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <span>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model.trim="form.name" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model.trim="form.code" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select
              v-model="form.manager"
              placeholder="请选择"
              @focus="focusEvent"
            >
              <el-option
                v-for="item in staff"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="form.introduce" />
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closePopout">取 消</el-button>
        <el-button type="primary" @click="verifyAll">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入接口
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments.js'

export default {
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      // 员工简单信息
      staff: [],
      // 控制弹框的显示与隐藏
      dialogVisible: false,
      //   树状数据中当前点击项的数据
      item: '',
      //   存储点击的是新增还是编辑
      mode: 'add',
      form: {
        name: '', // string	非必须		部门名称
        code: '', // string	非必须		部门编码，同级部门不可重复
        manager: '', // string	非必须		负责人名称
        introduce: '', //	string	非必须		介绍
        pid: ''
      },
      //   表单验证
      rules: {
        name: [
          { required: true, message: '此项为必填项目', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1——50个字符', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              let childrenList = []
              if (this.mode === 'add') {
                childrenList = this.initList.filter((i) => {
                  if (i.pid === this.item.id) {
                    return true
                  }
                })
              } else {
                childrenList = this.initList.filter((i) => {
                  if (i.pid === this.item.pid && i.id !== this.item.id) {
                    return true
                  }
                })
              }
              const repetition = childrenList.some((i) => {
                return i.name === value
              })
              repetition
                ? callback(new Error(`当前部门名称重复:${value}`))
                : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '此项为必填项目', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1——50个字符', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              let repetition = []
              if (this.mode === 'add') {
                repetition = this.initList.some((i) => {
                  return i.code === value
                })
              } else {
                repetition = this.initList.some((i) => {
                  return i.code === value && i.id !== this.item.id
                })
              }
              repetition
                ? callback(new Error(`当前部门编码重复:${value}`))
                : callback()
            },
            trigger: 'change'
          }
        ],
        manager: [
          { required: true, message: '此项为必填项目', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '此项为必填项目', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1——50个字符', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    dialogVisible(newval) {
      if (newval === false) {
        this.$refs.form.resetFields()
        this.form = {
          name: '',
          code: '',
          manager: '',
          introduce: '',
          pid: ''
        }
      }
    }
  },
  mounted() {
    this.$bus.$on('openPopout', (show, item, mode) => {
      this.dialogVisible = show
      this.item = item
      this.mode = mode
      if (this.mode === 'look') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('openPopout')
  },

  methods: {
    // 关闭弹框
    closePopout() {
      this.dialogVisible = false
    },
    // 选项框聚焦事件
    async focusEvent() {
      if (this.staff.length > 0) return

      const res = await sysUserSimple()
      //   console.log(res)
      this.staff = res.data
    },
    // 全局验证
    verifyAll() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            this.$message.success('添加成功')
          } else if (this.mode === 'look') {
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          this.dialogVisible = false
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
